package cn.iocoder.yudao.module.book.service.app;

import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.book.controller.app.vo.AppBookShelfCollectVO;
import cn.iocoder.yudao.module.book.dal.dataobject.bookshelfcollect.BookShelfCollectDO;
import cn.iocoder.yudao.module.book.dal.mysql.bookshelfcollect.BookShelfCollectMapper;
import jakarta.annotation.Resource;

@Service
public class AppBookShelfCollectServiceImpl implements AppBookShelfCollectService {

    @Resource
    private BookShelfCollectMapper bookShelfCollectMapper;

    @Override
    public List<AppBookShelfCollectVO> getListByCurrentUser() {

        return bookShelfCollectMapper.getListByCurrentUser(SecurityFrameworkUtils.getLoginUserId());
    }

    @Override
    public Boolean collectBook(Long bookId, Boolean isCollect) {

        if (isCollect) {
            LambdaQueryWrapper<BookShelfCollectDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BookShelfCollectDO::getUserId, SecurityFrameworkUtils.getLoginUserId()).eq(BookShelfCollectDO::getBookshelfId, bookId);
            int count = Math.toIntExact(bookShelfCollectMapper.selectCount(queryWrapper));
            if (count > 0) {
                return false;
            } else {
                BookShelfCollectDO bookShelfCollectDO = new BookShelfCollectDO();
                bookShelfCollectDO.setUserId(SecurityFrameworkUtils.getLoginUserId());
                bookShelfCollectDO.setBookshelfId(bookId);
                bookShelfCollectMapper.insert(bookShelfCollectDO);
                return true;
            }
        } else {
            LambdaQueryWrapper<BookShelfCollectDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BookShelfCollectDO::getUserId, SecurityFrameworkUtils.getLoginUserId()).eq(BookShelfCollectDO::getBookshelfId, bookId);
            bookShelfCollectMapper.delete(queryWrapper);
            return true;
        }

    }

    @Override
    public Boolean isCollectBook(Long bookId) {
        LambdaQueryWrapper<BookShelfCollectDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BookShelfCollectDO::getUserId, SecurityFrameworkUtils.getLoginUserId()).eq(BookShelfCollectDO::getBookshelfId, bookId);
        int count = Math.toIntExact(bookShelfCollectMapper.selectCount(queryWrapper));
        return count > 0;
    }

}
